#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "trianglemesh.h"

#include <QProgressBar>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow), tracer(0)
{
    ui->setupUi(this);

    progressBar = new QProgressBar(ui->statusBar);

    setImageResolution(800, 600);

}

MainWindow::~MainWindow()
{
    delete ui;
    delete tracer;
}

void MainWindow::setImageResolution(int width, int height)
{
    if (tracer != 0)
    {
        disconnect(this, SLOT(showProgess(int)));
        disconnect(this, SLOT(renderingFinished(QImage*)));
        delete this->tracer;
    }

    this->tracer = new Raytracer(width, height, this);

    connect(tracer, SIGNAL(updateProgess(int)), this, SLOT(showProgess(int)), Qt::AutoConnection);
    connect(tracer, SIGNAL(renderingFinished(QImage*)), this, SLOT(renderingFinished(QImage*)));

    ui->imageLabel->setMinimumWidth(width);
    ui->imageLabel->setMaximumWidth(width);
    ui->imageLabel->setMinimumHeight(height);
    ui->imageLabel->setMaximumHeight(height);

    this->centralWidget()->setMaximumHeight(height);
     this->centralWidget()->setMinimumHeight(height);
    //this->setMaximumHeight(height);
    //this->setMinimumHeight(height);
    this->setSizeIncrement(this->width(), height);
    this->updateGeometry();
    this->repaint();
}

void MainWindow::on_action250x250_triggered()
{
    setImageResolution(250, 250);
}

void MainWindow::on_action500x500_triggered()
{
    setImageResolution(500, 500);
}

void MainWindow::on_action640x480_triggered()
{
    setImageResolution(640, 480);
}

void MainWindow::on_action800x600_triggered()
{
    setImageResolution(800, 600);
}

void MainWindow::on_actionStartRayTracing_triggered()
{
    this->progressBar->setMaximum(tracer->width - 1);
    this->progressBar->setValue(0);
    TriangleMesh mesh;

    tracer->startRendering(0);
}

void MainWindow::showProgess(int percentageCompleted)
{
    this->progressBar->setValue(percentageCompleted);
}

void MainWindow::renderingFinished(QImage *image)
{
    ui->imageLabel->setPixmap(QPixmap::fromImage(*image));
}
